import signal
import multiprocessing
import time

class SocketServer:
    def __init__(self, running_event: multiprocessing.Event):
        """
        初始化 SocketServer 实例。

        Args:
            running_event (multiprocessing.Event): 用于控制服务运行/停止的共享事件
        """
        self.running_event = running_event

    def run(self):
        s = 0
        while self.running_event.is_set():
            s += 1
            time.sleep(1)
            print(f'[SocketServer]进程运行中...{s}', flush=True)
        print('[SocketServer]正在清理资源...', flush=True)
        time.sleep(2)
        print(f'[SocketServer]进程结束!', flush=True)


class SubscriberServer:
    """
    初始化 SubscriberServer 实例。

    Args:
        running_event (multiprocessing.Event): 用于控制服务运行/停止的共享事件
    """
    def __init__(self, running_event: multiprocessing.Event):
        self.running_event = running_event
        pass

    def run(self):
        s = 0
        while self.running_event.is_set():
            s += 1
            time.sleep(1)
            print(f'[SubscriberServer]进程运行中...{s}', flush=True)
        print('[SubscriberServer]正在清理资源...', flush=True)
        time.sleep(2)
        print(f'[SubscriberServer]进程运行结束!', flush=True)


def run_socket_server(running_event: multiprocessing.Event):
    """
    子进程入口函数：启动 SocketServer 服务。

    Args:
        running_event (multiprocessing.Event): 控制服务生命周期的事件
    """
    signal.signal(signal.SIGINT, signal.SIG_IGN)  # 进程内忽略信号
    server = SocketServer(running_event=running_event)
    server.run()


def run_subscriber_server(running_event: multiprocessing.Event):
    """
    子进程入口函数：启动 SubscriberServer 服务。

    Args:
        running_event (multiprocessing.Event): 控制服务生命周期的事件
    """
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    server = SubscriberServer(running_event=running_event)
    server.run()

def create_servers():
    """
    创建所有服务器进程并返回共享的关闭事件和进程列表。

    Returns:
        Tuple[Event, List[Process]]:
            - shutdown_event: 用于控制所有子进程退出的事件
            - processes: 所有已创建的子进程列表

    Example:
        shutdown_event, processes = create_servers()
        shutdown_event.set()
        for p in processes:
            p.start()
    """
    shutdown_event = multiprocessing.Event()
    socket_process = multiprocessing.Process(target=run_socket_server, args=(shutdown_event,), name='SocketServer')
    subscriber_process = multiprocessing.Process(target=run_subscriber_server, args=(shutdown_event,), name='SubscriberServer')
    return shutdown_event, [socket_process, subscriber_process]



if __name__ == '__main__':
    sd_event, processes = create_servers()
    sd_event.set()  # 将标志位设置为true，开始运行
    for p in processes:
        p.start()
    try:
        c = 0
        while True:
            """ 模拟一定条件下退出 """
            if c == 10:
                sd_event.clear()  # 将标志位设置为False
            time.sleep(1)
            c += 1
            print(f'主进程运行中...{c}', flush=True)
    except KeyboardInterrupt:
        print('主进程收到退出信号,正在退出', flush=True)
        """ 模拟收到退出信号的延迟执行状态,也看循环能不能继续 """
        time.sleep(2)
        sd_event.clear()  # 将标志位设置为False
        for p in processes:
            p.join(timeout=10)
    except Exception as e:
        print(f'主程序异常:{e}')
    finally:
        for p in processes:
            if p.is_alive():
                print(f"强制终止 {p.name}", flush=True)
                p.terminate()
                p.join()
        print("所有子进程已终止.程序退出.", flush=True)
